package com.zzgc.modules.controller;

import com.zzgc.common.entity.*;
import com.zzgc.common.response.HttpStatus;
import com.zzgc.common.response.Result;
import com.zzgc.common.utils.StringUtils;
import com.zzgc.modules.log.ApiLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.junit.Test;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据分析, 提供可视化界面数据
 *
 * @Author:
 * @CreateTime: 2022-12-02  17:27
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("analysis")
@ApiLog(value = "可视化分析类", url = "analysis")
@Api(tags = "可视化分析类")
public class DataAnalysisController extends BaseController {

    // 修改面板参数
    @PutMapping("edit/rate")
    public Result editRate(Long id, String unhealthy, String myopiaRate) {
        String userName = super.getUserName();
        String userRole = super.getUserRole();
        if (StringUtils.isNull(id)) {
            return Result.builder().code(500).msg("参数为空").build();
        }
        // 有一个不为空就修改
        if (StringUtils.isNotEmpty(unhealthy) || StringUtils.isNotEmpty(myopiaRate)) {
            if (userRole.equals("2")) { // 省级
                StaticProvincialVisualization provincialVisualization1 = provincialVisualizationService.queryById(id);
                if (!provincialVisualization1.getName().equals(userName)) {
                    return Result.builder().code(500).msg("只能修改本省数据！").build();
                }
                StaticProvincialVisualization provincialVisualization = new StaticProvincialVisualization();
                provincialVisualization.setId(id);
                provincialVisualization.setUnhealthyBackup(unhealthy);
                provincialVisualization.setMyopiaRateBackup(myopiaRate);
                provincialVisualizationService.update(provincialVisualization);
            }
            if (userRole.equals("3")) { // 市级
                StaticCityVisualization cityVisualization = cityVisualizationService.queryById(id);
                if (!cityVisualization.getCityName().equals(userName)) {
                    return Result.builder().code(500).msg("只能修改本市数据！").build();
                }
                StaticCityVisualization cityVisualization1 = new StaticCityVisualization();
                cityVisualization1.setId(id);
                cityVisualization1.setUnhealthyBackup(unhealthy);
                cityVisualization1.setMyopiaRateBackup(myopiaRate);
                cityVisualizationService.update(cityVisualization1);
            }
            if (userRole.equals("4")) { // 县级
                StaticDistrictVisualization districtVisualization = districtVisualizationService.queryById(id);
                if (!districtVisualization.getDistrictName().equals(userName)) {
                    return Result.builder().code(500).msg("只能修改本县数据！").build();
                }
                StaticDistrictVisualization districtVisualization1 = new StaticDistrictVisualization();
                districtVisualization1.setId(id);
                districtVisualization1.setUnhealthy(unhealthy);
                districtVisualization1.setMyopiaRateBackup(myopiaRate);
                districtVisualizationService.update(districtVisualization1);
            }
            return Result.builder().code(HttpStatus.OK.value())
                    .msg(HttpStatus.OK.getReasonPhrase()).build();
        }
        return Result.builder().code(500).msg("参数为空").build();
    }

    // 恢复面板参数
    @GetMapping("restore")
    public Result restore(Long id, Integer type) {
        String userRole = super.getUserRole();
        String userName = super.getUserName();
        if (StringUtils.isNull(id) || StringUtils.isNull(type)) {
            return Result.builder().code(500).msg("参数不能为空！").build();
        }
        Map<String, String> hashMap = new HashMap<>();
        if (userRole.equals("2")) { // 省级
            StaticProvincialVisualization provincialVisualization1 = provincialVisualizationService.queryById(id);
            if (!provincialVisualization1.getName().equals(userName)) {
                return Result.builder().code(500).msg("只能修改本省数据！").build();
            }
            if (type == 1) {
                provincialVisualizationService.restoreUnhealthy(id);
            }
            if (type == 2) {
                provincialVisualizationService.restoreMyopiaRate(id);
            }
            hashMap.put("unhealthy", provincialVisualization1.getUnhealthy());
            hashMap.put("myopiaRate", provincialVisualization1.getMyopiaRate());
        }
        if (userRole.equals("3")) { // 市级
            StaticCityVisualization cityVisualization = cityVisualizationService.queryById(id);
            if (!cityVisualization.getCityName().equals(userName)) {
                return Result.builder().code(500).msg("只能修改本市数据！").build();
            }
            if (type == 1) {
                cityVisualizationService.restoreUnhealthy(id);
            }
            if (type == 2) {
                cityVisualizationService.restoreMyopiaRate(id);
            }
            hashMap.put("unhealthy", cityVisualization.getUnhealthy());
            hashMap.put("myopiaRate", cityVisualization.getMyopiaRate());
        }
        if (userRole.equals("4")) { // 县级
            StaticDistrictVisualization districtVisualization = districtVisualizationService.queryById(id);
            if (!districtVisualization.getDistrictName().equals(userName)) {
                return Result.builder().code(500).msg("只能修改本县数据！").build();
            }
            if (type == 1) {
                districtVisualizationService.restoreUnhealthy(id);
            }
            if (type == 2) {
                districtVisualizationService.restoreMyopiaRate(id);
            }
            hashMap.put("unhealthy", districtVisualization.getUnhealthy());
            hashMap.put("myopiaRate", districtVisualization.getMyopiaRate());
        }
        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(hashMap).build();
    }


    /**
     * 筛查人数（总）
     * 筛查覆盖率（总）
     * 视力不良人数（总）
     * 视力不良率（总）
     * 近视人数（总）
     * 近视率（总）
     * 各市教育局学生人数，筛查率，视力不良率
     * 各校学生近视率排行TOP5
     * 男生异常人数
     * 男生异常占比
     * 女生异常人数
     * 女生异常占比
     * 裸眼视力人数
     */

    @GetMapping("get/provincial")
    @ApiLog(value = "获取省级可视化分析数据", url = "get/provincial", method = RequestMethod.GET)
    @ApiOperation(value = "获取省级可视化分析数据", notes = "获取省级可视化分析数据")
    public Result getProvincialAnalysis(String year, Integer number) {
        String userRole = super.getUserRole();
        //判断是否是河南省教育局
        if (userRole.matches("[^12]")) {
            return Result.builder().code(500).msg("暂无数据！").build();
        }
        if (StringUtils.isEmpty(year) || StringUtils.isNull(number)) {
            return Result.builder().code(500).msg("参数有空值！").build();
        }
        StaticProvincialVisualization provincialVisualization = new StaticProvincialVisualization();
        provincialVisualization.setYear(year);
        provincialVisualization.setNumber(number);
        // 查询省级数据分析
        List<StaticProvincialVisualization> provincialVisualizations = provincialVisualizationService.queryByPage(provincialVisualization);
        if (StringUtils.isEmpty(provincialVisualizations)) {
            return Result.builder().code(500).msg("暂无数据！").build();
        }
        StaticProvincialVisualization provincialVisualization1 = provincialVisualizations.get(0);
        // 判断是否显示备用数据
        if (StringUtils.isNotEmpty(provincialVisualization1.getUnhealthyBackup())) {
            provincialVisualization1.setUnhealthy(provincialVisualization1.getUnhealthyBackup());
        }
        if (StringUtils.isNotEmpty(provincialVisualization1.getMyopiaRateBackup())) {
            provincialVisualization1.setMyopiaRate(provincialVisualization1.getMyopiaRateBackup());
        }
        // 查询市级数据分析
        StaticCityVisualization cityVisualization = new StaticCityVisualization();
        cityVisualization.setYear(year);
        cityVisualization.setNumber(number);
        List<StaticCityVisualization> cityVisualizations = cityVisualizationService.queryByPage(cityVisualization);
        for (StaticCityVisualization visualization : cityVisualizations) {
            // 判断是否显示备用数据
            if (StringUtils.isNotEmpty(visualization.getUnhealthyBackup())) {
                visualization.setUnhealthy(visualization.getUnhealthyBackup());
            }
            if (StringUtils.isNotEmpty(visualization.getMyopiaRateBackup())) {
                visualization.setMyopiaRate(visualization.getMyopiaRateBackup());
            }
        }
        provincialVisualization1.setCitys(cityVisualizations); // 添加市级数据
        // 查询全省学校数据分析，根据学校分组，条件是年份和筛查次数
        StaticSchoolVisualization school = new StaticSchoolVisualization();
        school.setYear(year);
        school.setNumber(number);
        List<StaticSchoolVisualization> staticSchoolVisualizations = schoolVisualizationService.queryCountSum(school);
        // 计算学校近视率
        staticSchoolVisualizations = calculationSchool(staticSchoolVisualizations);
        staticSchoolVisualizations.sort(new Comparator<StaticSchoolVisualization>() { // 对近视率排序
            @Override
            public int compare(StaticSchoolVisualization o1, StaticSchoolVisualization o2) {
                float f1 = Float.parseFloat(o1.getMyopiaRate()) * 10;
                float f2 = Float.parseFloat(o2.getMyopiaRate()) * 10;
                return (int) f2 - (int) f1;
            }
        });
        if (staticSchoolVisualizations.size() > 5) { // 长度大于5就截取
            provincialVisualization1.setSchools(staticSchoolVisualizations.subList(0, 5));// 截取TOP5
        } else {
            provincialVisualization1.setSchools(staticSchoolVisualizations); // 添加学校近视率列表
        }
        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(provincialVisualization1).build();
    }

    @GetMapping("get/school/type")
    @ApiLog(value = "根据学校类型统计年级近视率和不良率", url = "get/school/type", method = RequestMethod.GET)
    @ApiOperation(value = "根据学校类型统计年级近视率和不良率", notes = "根据学校类型统计年级近视率和不良率")
    public Result getSchoolTypeAnalysis(String year, Integer number, String type, String city, String district) {
        //获取当前的城市信息
        String dist = super.getDepartId();
        AuthDepart depart = departService.queryById(Long.parseLong(dist));
        String city1 = depart.getAIdBak();
        String userRole = super.getUserRole();

        //判断是否是河南省教育局
//        if (!userRole.equals("1") && !userRole.equals("2")) {
//            //判断是否是区级，前端传参city参数为当前点击地区
//            if (!userRole.equals("3")) {
//                //查询是否为当前县的数据
//                if (!city1.equals(district)) {
//                    return Result.builder().code(500).msg("请查询本区域的数据!").build();
//                }
//            }else if (!city1.equals(city)) {
//                return Result.builder().code(500).msg("请查询本区域的数据!").build();
//            }
//        }
        if (userRole.matches("[^12]") && (!city1.equals(userRole.equals("3") ? city : district))) {
            return Result.builder().code(500).msg("请查询本区域的数据!").build();
        }

        // 查询全省学校类型和年纪分组，根据学年，筛查次数，学校类型查询
        StaticSchoolVisualization visualization = new StaticSchoolVisualization();
        visualization.setYear(year);
        visualization.setNumber(number);
        visualization.setType(type);
        visualization.setCity(city); // 市级查询添加市级参数
        visualization.setDistrict(district); // 区县查询添加区县参数和市级参数
        List<StaticSchoolVisualization> schoolVisualizationList = schoolVisualizationService.queryTypeCountSum(visualization);
        schoolVisualizationList = calculationSchool(schoolVisualizationList);
        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(schoolVisualizationList).build();
    }

    // 计算学校近视率不良率和覆盖率
    private List<StaticSchoolVisualization> calculationSchool(List<StaticSchoolVisualization> schools) {
        for (StaticSchoolVisualization staticSchoolVisualization : schools) {
            // 覆盖率 = 学校筛查人数 / 学校总数
            staticSchoolVisualization.setCoverage(asyncStatistical.keepDecimals(1, staticSchoolVisualization.getInspect() / (float) staticSchoolVisualization.getCount()));
            // 不良率 = 不良人数 / 筛查人数
            staticSchoolVisualization.setUnhealthy(asyncStatistical.keepDecimals(1, staticSchoolVisualization.getAbnormalVision() / (float) staticSchoolVisualization.getInspect()));
            // 近视率 = 近视人数 / 筛查人数
            staticSchoolVisualization.setMyopiaRate(asyncStatistical.keepDecimals(1, staticSchoolVisualization.getMyopia() / (float) staticSchoolVisualization.getInspect()));
        }
        return schools;
    }

    @GetMapping("get/city")
    @ApiLog(value = "获取城市可视化数据", url = "get/city", method = RequestMethod.GET)
    @ApiOperation(value = "获取城市可视化数据", notes = "获取城市可视化数据")
    public Result getCityAnalysis(String year, Integer number, String city) {
        //获取当前的城市信息
        String dist = super.getDepartId();
        AuthDepart depart = departService.queryById(Long.parseLong(dist));
        String city1 = depart.getAIdBak();
        String userRole = super.getUserRole();
        //判断是否是河南省教育局
        if (userRole.matches("[^12]") && !city1.equals(city)) {
            return Result.builder().code(500).msg("请查询本区域的数据!").build();
        }
        if (StringUtils.isEmpty(year) || StringUtils.isNull(number) || StringUtils.isEmpty(city) && !userRole.equals("1") && !userRole.equals("2")) {
            return Result.builder().code(500).msg("参数有空值！").build();
        }
        StaticCityVisualization cityVisualization = new StaticCityVisualization();
        cityVisualization.setYear(year);
        cityVisualization.setNumber(number);
        cityVisualization.setCity(city);
        List<StaticCityVisualization> cityVisualizations = cityVisualizationService.queryByPage(cityVisualization);
        if (StringUtils.isEmpty(cityVisualizations)) {
            return Result.builder().code(500).msg("暂无数据！").build();
        }
        StaticCityVisualization cityVisualization1 = cityVisualizations.get(0);
        // 判断是否显示备用数据
        if (StringUtils.isNotEmpty(cityVisualization1.getUnhealthyBackup())) {
            cityVisualization1.setUnhealthy(cityVisualization1.getUnhealthyBackup());
        }
        if (StringUtils.isNotEmpty(cityVisualization1.getMyopiaRateBackup())) {
            cityVisualization1.setMyopiaRate(cityVisualization1.getMyopiaRateBackup());
        }
        // 查询全市区县数据分析
        StaticDistrictVisualization districtVisualization = new StaticDistrictVisualization();
        districtVisualization.setYear(year);
        districtVisualization.setNumber(number);
        districtVisualization.setCity(city);
        List<StaticDistrictVisualization> visualizations = districtVisualizationService.queryByPage(districtVisualization);
        for (StaticDistrictVisualization visualization : visualizations) {
            // 判断是否显示备用数据
            if (StringUtils.isNotEmpty(visualization.getUnhealthyBackup())) {
                visualization.setUnhealthy(visualization.getUnhealthyBackup());
            }
            if (StringUtils.isNotEmpty(visualization.getMyopiaRateBackup())) {
                visualization.setMyopiaRate(visualization.getMyopiaRateBackup());
            }
        }
        cityVisualization1.setCitys(visualizations); // 添加区县数据

        // 查询全市学校数据分析，根据学校分组，条件是年份和筛查次数和城市
        StaticSchoolVisualization school = new StaticSchoolVisualization();
        school.setYear(year);
        school.setNumber(number);
        school.setCity(city);
        List<StaticSchoolVisualization> staticSchoolVisualizations = schoolVisualizationService.queryCountSum(school);
        staticSchoolVisualizations = calculationSchool(staticSchoolVisualizations);

        staticSchoolVisualizations.sort(new Comparator<StaticSchoolVisualization>() { // 对近视率排序
            @Override
            public int compare(StaticSchoolVisualization o1, StaticSchoolVisualization o2) {
                float f1 = Float.parseFloat(o1.getMyopiaRate()) * 10;
                float f2 = Float.parseFloat(o2.getMyopiaRate()) * 10;
                return (int) f2 - (int) f1;
            }
        });
        if (staticSchoolVisualizations.size() > 5) { // 长度大于5就截取
            cityVisualization1.setSchools(staticSchoolVisualizations.subList(0, 5));// 截取TOP5
        } else {
            cityVisualization1.setSchools(staticSchoolVisualizations); // 添加学校列表
        }

        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(cityVisualization1).build();
    }

    @GetMapping("get/district")
    @ApiLog(value = "获取区县可视化数据", url = "get/district", method = RequestMethod.GET)
    @ApiOperation(value = "获取区县可视化数据", notes = "获取区县可视化数据")
    public Result getDistrictAnalysis(String year, Integer number, String city, String district) {
        String userRole = super.getUserRole();
        //获取当前的城市信息
        String dist = super.getDepartId();
        AuthDepart depart = departService.queryById(Long.parseLong(dist));
        String city1 = depart.getAIdBak();
        if (userRole.matches("[^12]") && (!city1.equals(userRole.equals("3") ? city : district))) {
            return Result.builder().code(500).msg("请查询本区域的数据!").build();
        }

        if (StringUtils.isEmpty(year) || StringUtils.isNull(number) || StringUtils.isEmpty(city) || StringUtils.isEmpty(district)) {
            return Result.builder().code(500).msg("参数有空值！").build();
        }
        // 查询全市区县数据分析
        StaticDistrictVisualization districtVisualization = new StaticDistrictVisualization();
        districtVisualization.setYear(year);
        districtVisualization.setNumber(number);
        districtVisualization.setCity(city);
        districtVisualization.setDistrict(district);
        List<StaticDistrictVisualization> visualizations = districtVisualizationService.queryByPage(districtVisualization);

        StaticDistrictVisualization districtVisualization1 = visualizations.get(0);
        // 判断是否显示备用数据
        if (StringUtils.isNotEmpty(districtVisualization1.getUnhealthyBackup())) {
            districtVisualization1.setUnhealthy(districtVisualization1.getUnhealthyBackup());
        }
        if (StringUtils.isNotEmpty(districtVisualization1.getMyopiaRateBackup())) {
            districtVisualization1.setMyopiaRate(districtVisualization1.getMyopiaRateBackup());
        }
        // 查询区县学校数据分析，根据学校分组，条件是年份和筛查次数和城市和区县
        StaticSchoolVisualization school = new StaticSchoolVisualization();
        school.setYear(year);
        school.setNumber(number);
        school.setCity(city);
        school.setDistrict(district);
        List<StaticSchoolVisualization> staticSchoolVisualizations = schoolVisualizationService.queryCountSum(school);
        staticSchoolVisualizations = calculationSchool(staticSchoolVisualizations); // 计算占比，不用获取TOP
        staticSchoolVisualizations.sort(new Comparator<StaticSchoolVisualization>() { // 对近视率排序
            @Override
            public int compare(StaticSchoolVisualization o1, StaticSchoolVisualization o2) {
                float f1 = Float.parseFloat(o1.getMyopiaRate()) * 10;
                float f2 = Float.parseFloat(o2.getMyopiaRate()) * 10;
                return (int) f2 - (int) f1;
            }
        });
        districtVisualization1.setSchools(staticSchoolVisualizations); // 添加学校列表
        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(districtVisualization1).build();
    }

//   @GetMapping("get/RoleInfo")
//    public Integer getRoleInfo() {
//       String userName = super.getUserName();
//       if (userName.equals("河南省教育局")) {
//           System.out.println(1);
//           return 1;
//       }else{
//           System.out.println(2);
//           return 2;
//       }
//    }
}
